//
//  SlideshowImageView.swift
//  QZWM_User_new
//
//  Created by youai on 2019/4/15.
//  Copyright © 2019年 youi. All rights reserved.
//

import Foundation
import UIKit

class SlideshowImageView<T> : UIScrollView,UIScrollViewDelegate {
    
    let leftImage = UIImageView()
    let centerImage = UIImageView()
    let rightImage = UIImageView()
    
    let list : SlideshowData<T>
    private var timer : Timer? = nil
    func setList(_ list:[T]){
        self.list.list = list
        resetForCursor()
//        pointView?.resetList()
        self.delegate = self
    }
    
    func resetForCursor(){
        let (d1,d2,d3) = self.list.currentThree()
//        leftImage.setUrlOrHide(url: getImageUrl(data: d1) )
        setImage(image: leftImage, url: getImageUrl(data: d1))
//        centerImage.setUrlOrHide(url: getImageUrl(data: d2) )
        setImage(image: centerImage, url: getImageUrl(data: d2))
//        rightImage.setUrlOrHide(url: getImageUrl(data: d3) )
        setImage(image: rightImage, url: getImageUrl(data: d3))
        backToCenter()
    }
    
    init(cornerRadius:CGFloat,insetSize:CGFloat,defaultList:[T],imageMode:UIView.ContentMode = .scaleAspectFill){
        self.list = SlideshowData(defaultList: defaultList)
        super.init(frame: CGRect.zero)
        
        let leftContainer = UIView()
        self.addSubview(leftContainer)
        leftContainer.snp.makeConstraints { (make) in
            make.left.top.equalToSuperview()
            make.width.equalTo(self.snp.width)
            make.height.equalTo(self.snp.height)
        }
        leftContainer.addSubview(leftImage)
        leftImage.snp.makeConstraints { (make) in
            make.left.top.equalTo(insetSize)
            make.right.bottom.equalTo(-insetSize)
        }
        leftImage.cornerRadius(cornerRadius)
        leftImage.clipsToBounds = true
        leftImage.contentMode = imageMode
//        leftContainer.backgroundColor = .red

        let centerContainer = UIView()
        self.addSubview(centerContainer)
        centerContainer.snp.makeConstraints { (make) in
            make.top.equalToSuperview()
            make.left.equalTo(leftContainer.snp.right)
            make.width.equalTo(leftContainer.snp.width)
            make.height.equalTo(self.snp.height)
        }
        centerContainer.addSubview(centerImage)
        centerImage.snp.makeConstraints { (make) in
            make.left.top.equalTo(insetSize)
            make.right.bottom.equalTo(-insetSize)
        }
        centerImage.cornerRadius(cornerRadius)
        centerImage.clipsToBounds = true
        centerImage.contentMode = imageMode
//        centerImage.backgroundColor = .green
        
        let rightContainer = UIView()
        self.addSubview(rightContainer)
        rightContainer.snp.makeConstraints { (make) in
            make.top.equalToSuperview()
            make.left.equalTo(centerContainer.snp.right)
            make.width.equalTo(leftContainer.snp.width)
            make.height.equalTo(self.snp.height)
        }
        rightContainer.addSubview(rightImage)
        rightImage.snp.makeConstraints { (make) in
            make.left.top.equalTo(insetSize)
            make.right.bottom.equalTo(-insetSize)
        }
        rightImage.cornerRadius(cornerRadius)
        rightImage.clipsToBounds = true
        rightImage.contentMode = imageMode
//        rightImage.backgroundColor = .blue
        
        self.isPagingEnabled = true
        self.showsHorizontalScrollIndicator = false
    }
    
    func activateTap(){
        centerImage.isUserInteractionEnabled = true
        centerImage.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(_onCenterImageTap(tap:))))
    }
    
    @objc func _onCenterImageTap(tap:UITapGestureRecognizer){
        let (_,current,_) = list.currentThree()
        onCenterImageTap(data: current)
    }
    
    
    func startTimer(){
        if self.list.list.count == 1 {
//            self.pointView?.isHidden = true
//            self.isUserInteractionEnabled = false
            return
        }
        if timer != nil {
            stopTimer()
        }
        timer = Timer.scheduledTimer(withTimeInterval: 4.0, repeats: true
            , block: {[weak self] (_) in
                self?.onTimer()
        })
    }
    
    func stopTimer(){
        timer?.invalidate()
        timer = nil
    }
    
    func onTimer(){
        let now = Date()
        if now.timeIntervalSince1970 < skipTimerUntil {
            return
        }
        UIView.animate(withDuration: 0.5, animations: {
            self.contentOffset = CGPoint(x: self.bounds.width*2,y:0)
        }) { (_) in
            self.list.increaseCursor()
            self.resetForCursor()
//            self.pointView?.updatePosition()
            self.onUpdatePosition(cursor:self.list.cursor,count:self.list.list.count)
        }
    }
    
    override func layoutSubviews() {
        if self.bounds.width > 1 {
            let contentSize = CGSize(width: self.bounds.width*3, height: self.bounds.height)
            if self.contentSize != contentSize {
               self.contentSize = contentSize
               resetForCursor()
            }
        }
        super.layoutSubviews()
    }
    
    func backToCenter(){
        self.contentOffset = CGPoint(x:self.bounds.width,y:0)
    }
    
//    var pointView : SlidePointView<T>? = nil
//    func createSlidePointView(isGrayStyle:Bool)->SlidePointView<T> {
//        pointView = SlidePointView<T>(slideData: list,isGrayStyle:isGrayStyle)
//        return pointView!
//    }

    var skipTimerUntil : TimeInterval = 0
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView){
//        print(contentOffset)
        let now = Date()
        skipTimerUntil = now.timeIntervalSince1970 + 10.0
    }
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView){
        let currentPosition = contentOffset.x / contentSize.width
        if currentPosition <= 0.03 {
            self.list.decreaseCursor()
            self.resetForCursor()
//            self.pointView?.updatePosition()
            onUpdatePosition(cursor:list.cursor,count:list.list.count)
        }else if currentPosition >= 2.0/3.0 - 0.03 {
            self.list.increaseCursor()
            self.resetForCursor()
//            self.pointView?.updatePosition()
            onUpdatePosition(cursor:list.cursor,count:list.list.count)
        }
        let now = Date()
        skipTimerUntil = now.timeIntervalSince1970 + 1.0
    }
    
    //协议部分
    //从数据中获取url
    func getImageUrl(data:T)->String?{
        return nil
    }
    //向image设置url
    func setImage(image:UIImageView,url:String?){
        
    }
    //更新页面的时候触发
    func onUpdatePosition(cursor:Int,count:Int){
        
    }
    //触碰图片的时候触发
    func onCenterImageTap(data:T){
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

//MARK : SlideshowData
class SlideshowData<T>{
    
    let defaultList : [T]
    private var _var : [T]
    var list : [T] {
        get{return _var}
        set(newList){
            if newList.count==0{
                _var = defaultList
            }else{
                _var = newList
            }
            cursor = 0
        }
    }
    
    fileprivate(set) var cursor:Int = 0
    
    init(defaultList:[T]){
        assert(defaultList.count>0)
        self.defaultList = defaultList
        self._var = defaultList
    }
    
    func increaseCursor(){
        cursor += 1
        if cursor >= list.count {
            cursor = 0
        }
    }
    
    func decreaseCursor(){
        cursor -= 1
        if cursor<0 {
            cursor += list.count
        }
    }
    
    func currentThree()->(T,T,T) {
        return (getData(offset:-1),getData(offset: 0),getData(offset: +1))
    }
    
    func currentTwo()->(T,T){
        return (getData(offset: 0),getData(offset: +1))
    }
    
    func getData(offset:Int)->T{
        var nextCursor = cursor+offset
        while nextCursor >= list.count {
            nextCursor -= list.count
        }
        while(nextCursor<0){
            nextCursor += list.count
        }
        return list[nextCursor]
    }
    
    
}

//class SlidePointView<T> : UIView {
//
//    var pointList = [SlidePointView_Point]()
//    let slideData : SlideshowData<T>
//    let isGrayStyle : Bool
//    init(slideData : SlideshowData<T>,isGrayStyle : Bool){
//        self.slideData = slideData
//        self.isGrayStyle = isGrayStyle
//        super.init(frame: CGRect.zero)
//        self.layer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
//    }
//
//    func resetList(){
//        pointList.forEach { $0.removeFromSuperview() }
//        pointList.removeAll()
//        let width = slideData.list.count * (4 + 5)// + 4
//        self.bounds = CGRect(origin: .zero, size: .init(width: width, height: 5))
//        var x : CGFloat = 2.0 //宽度是4，第一个的相对位置是2.0
//        for i in 0..<slideData.list.count {
//            let point = SlidePointView_Point(isGrayStyle: isGrayStyle)
//            self.addSubview(point)
//            pointList.append(point)
//            if i==slideData.cursor { //如果就是当前的点
//                point.center = CGPoint(x: x+2.0, y: 2.5)
//                x += 4.0
//                point.isSelected = true
//            }else{
//                point.center = CGPoint(x: x, y: 2.5)
//            }
//            x += 4+5
//        }
//    }
//
//    func updatePosition(){
//        var x : CGFloat = 2.0 //宽度是4，第一个的相对位置是2.0
//        for i in 0..<slideData.list.count {
//            let point = pointList[i]
//            if i==slideData.cursor { //如果就是当前的点
//                point.center = CGPoint(x: x+2.0, y: 2.5)
//                x += 4.0
//                point.isSelected = true
//            }else{
//                point.center = CGPoint(x: x, y: 2.5)
//                point.isSelected = false
//            }
//            x += 4+5
//        }
//    }
//
//
//    required init?(coder aDecoder: NSCoder) {
//        fatalError("init(coder:) has not been implemented")
//    }
//}
//
//class SlidePointView_Point : UIView {
//
//    var isSelected : Bool = false {
//        didSet{
//            selectedView.isHidden = !isSelected
//            deselectedView.isHidden = isSelected
//        }
//    }
//
//    let selectedView = UIView()
//    let deselectedView = UIView()
//
//    init(isGrayStyle:Bool){
//        super.init(frame: CGRect(x: 0, y: 0, width: 8, height: 5))
//        addSubview(selectedView)
//        selectedView.frame = CGRect(x: 0, y: 0.5, width: 8, height: 4)
//        selectedView.backgroundColor = .xEA3232
//        selectedView.cornerRadius(2.0)
//        selectedView.isHidden  = true
//        addSubview(deselectedView)
//        let pointSize : CGFloat = 4.5
//        deselectedView.frame = CGRect(x: (8-pointSize)*0.5, y: (5-pointSize)*0.5, width: pointSize, height: pointSize)
//        deselectedView.cornerRadius(pointSize*0.5)
//        if isGrayStyle {
//            deselectedView.backgroundColor = .xE3E3E3
//        }else{
//            deselectedView.border(width: 1.0, color: .white)
//        }
//        self.layer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
//    }
//
//    required init?(coder aDecoder: NSCoder) {
//        fatalError("init(coder:) has not been implemented")
//    }
//}
